package com.jinxin.platform.cdperprotypay.controller;

import com.alibaba.excel.EasyExcel;
import com.jinxin.platform.base.common.pojo.JsonResult;
import com.jinxin.platform.cdperprotypay.excel.ColumnWidthStyleStrategy;
import com.jinxin.platform.cdperprotypay.excel.data.MeterDatas;
import com.jinxin.platform.cdperprotypay.excel.listener.MeterDataReadListener;
import com.jinxin.platform.cdperprotypay.mapper.MeterDataMapper;
import com.jinxin.platform.cdperprotypay.pojo.bo.SysHouse;
import com.jinxin.platform.cdperprotypay.pojo.bo.WaterData;
import com.jinxin.platform.cdperprotypay.pojo.domain.MeterData;
import com.jinxin.platform.cdperprotypay.pojo.form.MeterDateForm;
import com.jinxin.platform.cdperprotypay.service.MeterDataService;
import com.jinxin.platform.cdperprotypay.support.ModularSupport;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author : zhangpeng
 * @date : 2020-07-01 17:37:38
 **/
@Slf4j
@RestController
@RequestMapping("cdpropertypay/meter")
public class MeterDataController {

    @Resource
    private MeterDataService meterDataService;

    @Resource
    private MeterDataMapper meterDataMapper;

    @Resource
    private ModularSupport modularSupport;

    @PostMapping("/inputExcel")
    public JsonResult inputUserByExcel(String villageId,HttpServletRequest request, @RequestParam(value = "file", required = false) MultipartFile file) {
        MeterDataReadListener meterDataReadListener = new MeterDataReadListener(villageId);
        try {
            InputStream inputStream = file.getInputStream();
            EasyExcel.read(inputStream, MeterDatas.class, meterDataReadListener).sheet().headRowNumber(1).doRead();
        } catch (Exception e) {
            log.error("文件获取流异常:{}", e.getMessage());
            if (meterDataReadListener.map.size() != 0){
                return JsonResult.error(meterDataReadListener.map.get("msg"));
            }
            return JsonResult.error("文件异常,请正确填写或者选择文件!");
        }

        return JsonResult.ok("导入成功！", null);
    }

    @GetMapping("/outputExcel")
    public void outputExcel(HttpServletResponse response,String villageId,String type,String itemsId) throws IOException {
        ArrayList<MeterDatas> meterDatas = new ArrayList<>();
        HashMap<Object, Object> map = new HashMap<>();
        map.put("villageId",villageId);
        List<SysHouse> allHouse = modularSupport.getAllHouse(map);

        for (SysHouse s : allHouse) {
            MeterDatas datas = new MeterDatas();
            datas.setVillageId(villageId);
            datas.setRoomId(s.getRoomId());
            datas.setRooms(s.getBuildName()+"-"+s.getRoomName());
            datas.setItemsId(itemsId);
            datas.setMeterItems(type);
            meterDatas.add(datas);
        }

        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode(type+"抄表数据", "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        // 这里需要设置不关闭流
        EasyExcel.write(response.getOutputStream(), MeterDatas.class).registerWriteHandler(new ColumnWidthStyleStrategy()).sheet(type).doWrite(meterDatas);
    }

    @PostMapping("/pageList")
    public JsonResult pageList(MeterDateForm meterDateForm){
        return meterDataService.pageList(meterDateForm);
    }

    @PostMapping("/water")
    public JsonResult water(String dataTime,String villageId){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String[] split = dataTime.split("-");
        String startTime = getFirstDayOfMonth1(Integer.parseInt(split[0]),Integer.parseInt(split[1]));
        String endTime = getLastDayOfMonth1(Integer.parseInt(split[0]),Integer.parseInt(split[1]));
        Map<String,String> map = new HashMap<>();
        map.put("villageId",villageId);
        List<SysHouse> allHouse = modularSupport.getAllHouse(map);
        for (SysHouse sysHouse : allHouse) {
            Map<String,String> wmap = new HashMap<>();
            wmap.put("sTime",startTime);
            wmap.put("eTime",endTime);
            wmap.put("roomId",sysHouse.getRoomId());
            List<WaterData> waterData = modularSupport.getWaterData(wmap);
            log.info("获取的水表数据：{}",waterData);
            String cus = "0.00";
            boolean flag = false;

            if (waterData.size() == 0){
                continue;
            }

            for (WaterData water : waterData) {
                try {
                    if(isEffectiveDate(sdf.parse(water.getDataTime()),sdf.parse(startTime),sdf.parse(endTime))){
                       cus = String.format("%.2f",add(cus, water.getConsumption()));
                       flag = true;
                    }
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }

            MeterData meterData = new MeterData();
            meterData.setRoomId(sysHouse.getRoomId());
            try {
                meterData.setMeterStime(sdf.parse(startTime));
            } catch (ParseException e) {
                e.printStackTrace();
            }
            List<MeterData> meterDataList = meterDataMapper.queryAll(meterData);

            try {
                meterData.setMeterStime(sdf.parse(startTime));
                meterData.setMeterEtime(sdf.parse(endTime));
                meterData.setMeterEdata("/");
                meterData.setMeterSdata("/");
                meterData.setMeterItems("水费");
                meterData.setVillageId(villageId);
            } catch (ParseException e) {
                e.printStackTrace();
            }

            if(meterDataList.size() == 0){  //当前房间没有数据，直接插入
                meterData.setConsumption(cus);
                meterDataService.insert(meterData);
            }else { //存在房间
                for (MeterData m : meterDataList) {
                    try {
                        if(flag)meterData.setConsumption(cus); // 如果当前月返回水表数据，重置用量
                        //判断同步月份是否存在并且存在数据是否是同步月份
                        if(m.getMeterItems().equals("水费") && isEffectiveDate(m.getMeterStime(),sdf.parse(startTime),sdf.parse(endTime))){
                            meterData.setId(m.getId());
                            meterDataService.update(meterData); //正确，覆盖数据
                        }
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }
            }

        }

        return JsonResult.ok();
    }

    /**
     18      * 提供精确的加法运算。
     19      *
     20      * @param value1 被加数
     21      * @param value2 加数
     22      * @return 两个参数的和
     23      */
    public static Double add(String value1, String value2) {
        BigDecimal b1 = new BigDecimal(value1);
        BigDecimal b2 = new BigDecimal(value2);
        return b1.add(b2).doubleValue();
    }

    public static String getFirstDayOfMonth1(int year, int month) {
        Calendar cal = Calendar.getInstance();
        //设置年份
        cal.set(Calendar.YEAR, year);
        //设置月份
        cal.set(Calendar.MONTH, month-1);
        //获取某月最小天数
        int firstDay = cal.getMinimum(Calendar.DATE);
        //设置日历中月份的最小天数
        cal.set(Calendar.DAY_OF_MONTH,firstDay);
        cal.set(Calendar.HOUR_OF_DAY,0);
        cal.set(Calendar.MINUTE,0);
        cal.set(Calendar.SECOND,0);
        //格式化日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.format(cal.getTime());
    }

    public static String getLastDayOfMonth1(int year, int month) {
        Calendar cal = Calendar.getInstance();
        //设置年份
        cal.set(Calendar.YEAR, year);
        //设置月份
        cal.set(Calendar.MONTH, month-1);
        //获取某月最大天数
        int lastDay = cal.getActualMaximum(Calendar.DATE);
        //设置日历中月份的最大天数
        cal.set(Calendar.DAY_OF_MONTH, lastDay);
        cal.set(Calendar.HOUR_OF_DAY,23);
        cal.set(Calendar.MINUTE,59);
        cal.set(Calendar.SECOND,59);
        //格式化日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.format(cal.getTime());
    }

    /**
     *
     * @param nowTime   当前时间
     * @param startTime	开始时间
     * @param endTime   结束时间
     * @return
     * @author sunran   判断当前时间在时间区间内
     */
    public static boolean isEffectiveDate(Date nowTime, Date startTime, Date endTime) {
        if (nowTime.getTime() == startTime.getTime() || nowTime.getTime() == endTime.getTime()) {
            return true;
        }

        Calendar date = Calendar.getInstance();
        date.setTime(nowTime);

        Calendar begin = Calendar.getInstance();
        begin.setTime(startTime);

        Calendar end = Calendar.getInstance();
        end.setTime(endTime);

        if (date.after(begin) && date.before(end)) {
            return true;
        } else {
            return false;
        }
    }

    public static void main(String[] args) {
        String dataTime = "2020-10";
        String[] split = dataTime.split("-");
        String startTime = getFirstDayOfMonth1(Integer.parseInt(split[0]),Integer.parseInt(split[1]));
        String endTime = getLastDayOfMonth1(Integer.parseInt(split[0]),Integer.parseInt(split[1]));
//        System.out.println(startTime);
//        System.out.println(endTime);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            boolean effectiveDate = isEffectiveDate(sdf.parse("2020-02-10 12:20:11"), sdf.parse(startTime), sdf.parse(endTime));
            System.out.println(effectiveDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
}
